/*
** parse_option.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Tue Jul  5 10:21:24 2011 michael guidet
** Last update Tue Jul  5 13:23:11 2011 michael guidet
*/

#include "server.h"

void	parse_check_team(int j, char **av, t_env *e, int deb)
{
  e->teams[j].name = av[deb + j];
  if (!strcmp(e->teams[j].name, "GRAPHIC"))
    aff_err("INVALID TEAM NAME");
  if (strlen(e->teams[j].name) > 15)
    aff_err("TEAM NAME to long");
  e->teams[j].dispo = 0;
  e->teams[j].ia_players = NULL;
  e->teams[j].eggs = NULL;
}

void	parse_team_name(t_env *e, int ac, char **av, int *i)
{
  int	j;
  int	deb;
  int	nb_team;

  deb = *i + 1;
  nb_team = 0;
  for (j = *i + 1; j < ac; j++)
    {
      if (!strcmp(av[j], "-p") || !strcmp(av[j], "-x") || !strcmp(av[j], "-y")
	  || !strcmp(av[j], "-c") || !strcmp(av[j], "-t")
	  || !strcmp(av[j], "-n"))
	break;
      nb_team++;
    }
  if (nb_team < 2)
    aff_err("You have to specify at least two teams");
  *i = j - 1;
  e->teams = x_null(NULL, malloc(sizeof(*(e->teams)) * (nb_team + 1)),
		    "malloc");
  for (j = 0; j < nb_team; j++)
    parse_check_team(j, av, e, deb);
  e->teams[j].name = NULL;
}

int	parse_number(char *str)
{
  int	i;

  for (i = 0; str[i]; i++)
    {
      if (str[i] < '0' || str[i] > '9')
	{
	  fprintf(stderr, "This is not a number\n");
	  exit(EXIT_FAILURE);
	}
    }
  if (strlen(str) > 8)
    {
      fprintf(stderr, "Too high number\n");
      exit(EXIT_FAILURE);
    }
  return (atoi(str));
}

void	parse_check_value(t_env *e)
{
  if (e->width < 10 || e->width > 999)
    aff_err("Width must be between 10 and 999");
  if (e->height < 10 || e->height > 999)
    aff_err("Height must be between 10 and 999");
  if (e->t == 0)
    aff_err("Time is null");
  if (e->t > 500)
    aff_err("T is too high , set it  between 1 and 500");
}

void	parse_option(t_env *e, int ac, char **av, int i)
{
  set_default(e);
  for (i = 1; i < ac; i++)
    {
      if (!strcmp(av[i], "-p"))
	e->port = parse_number(av[++i]);
      else if (!strcmp(av[i], "-x"))
	e->width = parse_number(av[++i]);
      else if (!strcmp(av[i], "-y"))
	e->height = parse_number(av[++i]);
      else if (!strcmp(av[i], "-c"))
	e->max_connect = parse_number(av[++i]);
      else if (!strcmp(av[i], "-t"))
	e->t = parse_number(av[++i]);
      else if (!strcmp(av[i], "-n"))
	parse_team_name(e, ac, av, &i);
      else
	{
	  fprintf(stderr, "Unknow arg\n");
	  aff_err(USAGE);
	}
    }
  if (e->teams == NULL)
    aff_err("Please specify team name");
  parse_check_value(e);
}
